#include "gpio_buzzer.h"
#include "gd32f4xx.h"
#include "systick.h"
#include <stdio.h>

void buzzer_init()
{
    rcu_periph_clock_enable(RCU_GPIOB);
    gpio_mode_set(GPIOB, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN_9);
    gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN_9);
}

/**
 *  以频率为hz的持续duration的时间长度
 *	duration ms
 */
void buzzer_play(uint16_t hz, long duration)
{
    if (hz == 0)
    {
        delay_1ms(duration);
    }
    else
    {
        long times = (1000 * duration) / (HZ_DELAY(hz) * 2);
        for (int i = 0; i < times; i++)
        {
            buzzer_bi(hz);
        }
    }
}

void buzzer_bi(uint16_t hz)
{

    uint16_t hzDelay = HZ_DELAY(hz);
    gpio_bit_set(GPIOB, GPIO_PIN_9);
    delay_1us(hzDelay);
    gpio_bit_reset(GPIOB, GPIO_PIN_9);
    delay_1us(hzDelay);
}
